<?php

require_once LIBRARIES_ENTITIES_DATABASE;
require_once LIBRARIES_ENTITIES_ITEMS;
require_once LIBRARIES_ENTITIES_CATEGORIES;
require_once LIBRARIES_ENTITIES_PROPERTIES;
require_once LIBRARIES_ENTITIES_ITEMPROPERTIES;
require_once LIBRARIES_TOOLS_UTILITY;
require_once LIBRARIES_TOOLS_XTEMPLATE;
require_once LIBRARIES_TOOLS_PAGERBACKEND;

class ItemController {

    public function invoke() {


        // function list
        $groupFunctions = $_SESSION['groupFunctions'];

        // user login
        $userID = $_SESSION["session"]["sUserID"];


        // such as item, category
        $view = '';
        if (isset($_GET['view'])) {
            $view = $_GET['view'];
        }

        // such as: publish, unpublish, remove, add (addAnđExit), edit (editAndExit), 
        $action = '';
        if (isset($_POST['hdAction'])) {
            $action = $_POST['hdAction'];
        }

        // directory path
        $dir = dirname(__FILE__);

        // such as view, add, edit
        $task = '';
        if (isset($_GET['task'])) {
            $task = $_GET['task'];
        }

        // tổng số dòng muốn hiển thị
        $rowToView = 10;
        if (isset($_POST["limit"])) {
            $rowToView = $_POST["limit"];
        }


        if ($view == 'item') {


            switch ($action) {
                case 'publish':
                    $values = $_POST["cid"];
                    $result = $this->updateItemState($values, true);
                    break;
                case 'unpublish':
                    $values = $_POST["cid"];
                    $result = $this->updateItemState($values, false);
                    break;
                case 'orderdown':
                    $itemID = $_POST["hdItemID"];
                    $result = $this->orderItem($itemID, 'down');
                    break;
                case 'orderup':
                    $itemID = $_POST["hdItemID"];
                    $result = $this->orderItem($itemID, 'up');
                    break;
                case 'remove':
                    $values = $_POST["cid"];
                    $result = $this->deleteItem($values);
                    if ($result == OK) {
                        Utility::messageBox('Xóa thành công');
                    }
                    break;
                case 'add':
                case 'addAndExit':

                    // code
                    $code = $_POST['txtCode'];
                    // item name
                    $name = $_POST['txtName'];
                    // price
                    $price = $_POST['txtPrice'];
                    // alias
                    $alias = Utility::removeSigns($_POST['txtAlias']);
                    // image
                    $image = $_POST['hdImage'];
                    // category ID
                    $categoryID = $_POST['slCategoryID'];
                    // created date
                    $createdDate = Utility::formatDateTime($_POST['txtCreatedDate']);
                    // state of item
                    $state = $_POST['rdoState'];

                    // description
                    $description = Utility::replaceHtmlSpecialChars($_POST['txtDescription']);

                    // detail of item
                    $detail = Utility::replaceHtmlSpecialChars($_POST['txtContent']);

                    // initailize array item properties
                    $arrayItemProperties = array();



                    // string of property
                    $strProperty = $_POST['hdProperty'];

                    if ($strProperty != '') {
                        // convert string to array of property
                        $arrayProperty = explode(',', $strProperty);

                        // loop and add each property to array item properties
                        foreach ($arrayProperty as $property) {
                            $keyValueOfProperty = explode(':', $property);
                            $arrayItemProperties[] = $keyValueOfProperty;
                        }
                    }

                    // excetute add item
                    $result = $this->addItem($code, $name, $price, $categoryID, $image, $alias, $state, $createdDate, $userID, $description, $detail, $arrayItemProperties);

                    if ($result == OK) {
                        if ($action == 'add') {
                            Utility::messageBox('Thêm thành công');
                        } else {
                            Utility::redirect(".?com=com_item&view=item&task=view&categoryID=" . $_POST['slCategoryID'] . "");
                        }
                    }
                    break;
                case 'edit':
                case 'editAndExit':
                    // item id
                    $itemID = $_POST['hdItemID'];

                    // code
                    $code = $_POST['txtCode'];

                    // item name
                    $name = $_POST['txtName'];

                    // price
                    $price = $_POST['txtPrice'];

                    // alias
                    $alias = Utility::removeSigns($_POST['txtAlias']);

                    // image
                    $image = $_POST['hdImage'];

                    // category ID
                    $categoryID = $_POST['slCategoryID'];

                    // modified date
                    $modifiedDate = Utility::formatDateTime($_POST['txtModifiedDate']);

                    // state of item
                    $state = $_POST['rdoState'];

                    // description
                    $description = Utility::replaceHtmlSpecialChars($_POST['txtDescription']);

                    // detail of item
                    $detail = Utility::replaceHtmlSpecialChars($_POST['txtContent']);

                    // initailize array item properties
                    $arrayItemProperties = array();



                    // string of property
                    $strProperty = $_POST['hdProperty'];

                    if ($strProperty != '') {
                        // convert string to array of property
                        $arrayProperty = explode(',', $strProperty);

                        // loop and add each property to array item properties
                        foreach ($arrayProperty as $property) {
                            $keyValueOfProperty = explode(':', $property);
                            $arrayItemProperties[] = $keyValueOfProperty;
                        }
                    }

                    // excetute update item
                    $result = $this->updateItem($itemID, $code, $name, $price, $categoryID, $image, $alias, $state, $modifiedDate, $userID, $description, $detail, $arrayItemProperties);

                    if ($result == OK) {
                        if ($action == 'edit') {
                            Utility::messageBox('Cập nhật thành công');
                        } else {
                            Utility::redirect(".?com=com_item&view=item&task=view&categoryID=" . $_POST['slCategoryID'] . "");
                        }
                    }
                    break;
            }





            if ($task == 'view') {

                if (Utility::checkPermission('view', $groupFunctions, ITEM_MANAGEMENT)) {

                    $viewFile = $dir . DS . 'views' . DS . 'item' . DS . 'item_list.html';
                    $xtemplate = new XTemplate($viewFile);

                    // CHECK PERMISSION
                    // check add button
                    if (Utility::checkPermission('add', $groupFunctions, ITEM_MANAGEMENT)) {
                        $xtemplate->parse('main.add_button');
                    }
                    // check delete button
                    if (Utility::checkPermission('delete', $groupFunctions, ITEM_MANAGEMENT)) {
                        $xtemplate->parse('main.delete_button');
                    }
                    // check enable button
                    if (Utility::checkPermission('enable', $groupFunctions, ITEM_MANAGEMENT)) {
                        $xtemplate->parse('main.enable_button');
                    }
                    // check disable button
                    if (Utility::checkPermission('disable', $groupFunctions, ITEM_MANAGEMENT)) {
                        $xtemplate->parse('main.disable_button');
                    }



                    // category to filter
                    $categoryID = 0;
                    if (isset($_POST['slCategoryID'])) {
                        $categoryID = $_POST['slCategoryID'];
                    } else if (isset($_GET['categoryID'])) {
                        $categoryID = $_GET['categoryID'];
                    }

                    // index of checkbox
                    $indexCheckBox = 1;

                    // current page
                    $rurrentPage = 1;
                    if (isset($_POST["page"])) {
                        $rurrentPage = $_POST["page"];
                    }

                    // index of item
                    $index = 1;

                    // print category list
                    $this->printCategoryList($xtemplate);



                    // nếu có chọn category từ danh sách thì gán vào biến selectedcategoryID
                    // biến này dùng để truyền qua form thêm
                    if (isset($_POST['slCategoryID'])) {
                        $xtemplate->assign('SELECTED_CATEGORY_ID', $_POST['slCategoryID']);
                    } else {
                        $xtemplate->assign('SELECTED_CATEGORY_ID', 0);
                    }

                    // get item list
                    $items = $this->getItemListByCategoryID($categoryID);

                    // get pager object
                    $pager = PagerBackEnd::getPagerData(count($items), $rowToView, $rurrentPage);

                    if ($items != null) {
                        $indexCheckBox = 1;

                        // loop and print each item
                        foreach ($items as $item) {
                            if ($index > $pager->offset && $index <= $pager->limit) {

                                $xtemplate->assign('INDEX', $index);
                                $xtemplate->assign('INDEX_CHECKBOX', $indexCheckBox);
                                $xtemplate->assign('ITEM_ID', $item->getID());
                                $xtemplate->assign('ITEM_IMAGE', $item->getImage());
                                $xtemplate->assign('ITEM_CODE', $item->getCode());
                                $xtemplate->assign('ITEM_PRICE',  Utility::formatToCurrencyString($item->getPrice()));
                                $xtemplate->assign('ITEM_TITLE', $item->getName());
                                $xtemplate->assign('CATEGORY_TITLE', $item->getCategory()->getTitle());
                                $xtemplate->assign('CREATED_USER', $item->getCreatedUser()->getFullname());
                                $xtemplate->assign('MODIFIED_USER', $item->getModifiedUser()->getFullname());
                                $xtemplate->assign('CREATED_DATE', Utility::formatDateTimeToView($item->getCreatedDate()));
                                $xtemplate->assign('MODIFIED_DATE', Utility::formatDateTimeToView($item->getModifiedDate()));



                                // status
                                if ($item->getState() == 1) {
                                    $xtemplate->assign('STATUS_ACTION', 'unpublish');
                                    $xtemplate->assign('STATUS_IMAGE', 'publish_g.png');
                                } else {
                                    $xtemplate->assign('STATUS_ACTION', 'publish');
                                    $xtemplate->assign('STATUS_IMAGE', 'publish_r.png');
                                }



                                // check update permission                            
                                if (Utility::checkPermission('update', $groupFunctions, ITEM_MANAGEMENT)) {
                                    $xtemplate->parse('main.item_list.update_button');
                                } else {
                                    $xtemplate->parse('main.item_list.update_button_disable');
                                }

                                // order
                                // if the the first order then show the down arrow
                                if ($index == 1) {
                                    $xtemplate->parse('main.item_list.down_arrow');
                                }
                                // if the last order the show the up arrow
                                else if ($index == count($items)) {
                                    $xtemplate->parse('main.item_list.up_arrow');
                                }
                                // else show both arrow
                                else {
                                    $xtemplate->parse('main.item_list.up_down_arrow');
                                }

                                $xtemplate->parse('main.item_list');

                                $indexCheckBox++;
                            }
                            $index++;
                        }
                    }

                    // limit list
                    $xtemplate->assign('LIMIT_LIST', Utility::getLimitList($rowToView));

                    // show amount of row to view
                    $xtemplate->assign('ROW_TO_VIEW', $rowToView);

                    // show current page
                    $xtemplate->assign('CURRENT_PAGE', $rurrentPage);

                    // amount of item
                    $xtemplate->assign('AMOUNT_OF_ITEM', $pager->numPages);

                    // paging html
                    $xtemplate->assign('PAGING_HTML', $pager->paging);


                    $xtemplate->parse('main');
                    $xtemplate->out('main');
                } else {
                    echo ERROR_PERMISSION;
                }
            } else if ($task == 'add') {

                if (Utility::checkPermission('add', $groupFunctions, ITEM_MANAGEMENT)) {
                    $xtemplate = new XTemplate($dir . DS . 'views' . DS . 'item' . DS . 'item_add.html');

                    // print category list
                    $this->printCategoryList($xtemplate);

                    // print property list
                    $this->printPropertyList($xtemplate);

                    // current date
                    $xtemplate->assign('TODAY', date('d/m/Y'));

                    // folder path to upload
                    $xtemplate->assign('UPLOAD_FOLDER', UPLOAD_FOLDER);

                    $xtemplate->parse('main');
                    $xtemplate->out('main');
                } else {
                    echo ERROR_PERMISSION;
                }
            }
            // edit task
            else if ($task == 'edit') {

                if (Utility::checkPermission('update', $groupFunctions, ITEM_MANAGEMENT)) {
                    $xtemplate = new XTemplate($dir . DS . 'views' . DS . 'item' . DS . 'item_edit.html');

                    // item ID
                    $itemID = $_GET['itemID'];

                    // get detail of an item
                    $item = $this->getItemByID($itemID);


                    // print category list
                    $this->printCategoryList($xtemplate, $item->getCategoryID());

                    // print property list
                    $this->printPropertyList($xtemplate);



                    // get property list of item
                    $itemProperties = $this->getItemPropertiesByItemID($itemID);

                    if (count($itemProperties) > 0) {
                        $data = array();
                        for ($i = 0; $i < count($itemProperties); $i++) {
                            $row = array();
                            $row['itemID'] = $itemProperties[$i]->getItemID();
                            $row['propertyID'] = $itemProperties[$i]->getPropertyID();
                            $row['propertyName'] = $itemProperties[$i]->getProperty()->getName();
                            $row['value'] = $itemProperties[$i]->getValue();
                            $data[] = $row;
                        }
                        $xtemplate->assign('ARRAY_PROPERTY', json_encode($data));
                        $xtemplate->parse('main.push_array_property');
                    }

                    if ($item != null) {
                        $xtemplate->assign('ITEM_ID', $item->getID());
                        $xtemplate->assign('ITEM_CODE', $item->getCode());
                        $xtemplate->assign('ITEM_NAME', $item->getName());
                        $xtemplate->assign('ITEM_PRICE', $item->getPrice());
                        $xtemplate->assign('ITEM_IMAGE', $item->getImage());
                        $xtemplate->assign('ITEM_ALIAS', $item->getAlias());
                        $xtemplate->assign('ITEM_MODIFIED_DATE', $item->getModifiedDate());
                        $xtemplate->assign('ITEM_DESCRIPTION', $item->getDescription());
                        $xtemplate->assign('ITEM_DETAIL', $item->getDetail());
                    }

                    // folder path to upload
                    $xtemplate->assign('UPLOAD_FOLDER', UPLOAD_FOLDER);

                    $xtemplate->parse('main');
                    $xtemplate->out('main');
                } else {
                    echo ERROR_PERMISSION;
                }
            }
        }
        // view category
        else if ($view == 'category') {

            switch ($action) {
                case 'publish':
                    $values = $_POST["cid"];
                    $result = $this->updateCategoryState($values, true);
                    break;
                case 'unpublish':
                    $values = $_POST["cid"];
                    $result = $this->updateCategoryState($values, false);
                    break;
                case 'orderdown':
                    $categoryID = $_POST["hdCategoryID"];
                    $result = $this->orderCategory($categoryID, 'down');
                    break;
                case 'orderup':
                    $categoryID = $_POST["hdCategoryID"];
                    $result = $this->orderCategory($categoryID, 'up');
                    break;
                case 'remove':
                    $values = $_POST["cid"];
                    $result = $this->deleteCategory($values);
                    if ($result == OK) {
                        Utility::messageBox('Xóa thành công');
                    }
                    break;
                case 'add':
                case'addAndExit':
                    $title = $_POST['txtTitle'];
                    $alias = Utility::removeSigns($_POST['txtAlias']);
                    $description = Utility::replaceHtmlSpecialChars($_POST['txtDescription']);
                    $parent = $_POST['parentID'];
                    $createdDate = Utility::formatDateTime($_POST['createdDate']);
                    $status = $_POST['rdoState'];
                    $createdUserID = $userID;

                    $result = $this->addCategory($parent, $title, $alias, $createdDate, $description, $createdUserID, $status);

                    if ($result == OK) {
                        if ($action == 'add') {
                            Utility::messageBox('Thêm thành công');
                        } else {

                            Utility::redirect(".?com=com_item&view=category&task=view");
                        }
                    }
                    break;
                case 'edit':
                case 'editAndExit':
                    $categoryID = $_POST['hdCategoryID'];
                    $title = $_POST['txtTitle'];
                    $alias = Utility::removeSigns($_POST['txtAlias']);
                    $description = Utility::replaceHtmlSpecialChars($_POST['txtDescription']);
                    $parent = $_POST['slParentID'];
                    $createdDate = Utility::formatDateTime($_POST['createdDate']);
                    $status = $_POST['rdoState'];
                    $createdUserID = $userID;

                    $result = $this->updateCategory($parent, $title, $alias, $createdDate, $description, $createdUserID, $status, $categoryID);

                    if ($result == OK) {
                        if ($action == 'edit') {
                            Utility::messageBox('Sửa thành công');
                        } else {

                            Utility::redirect(".?com=com_item&view=category&task=view");
                        }
                    }
                    break;
            }









            // CHECK TASK
            // view task
            if ($task == 'view') {

                $viewFile = ADMIN_COM . DS . 'com_item' . DS . 'views' . DS . 'category' . DS . 'category_list.html';
                $xtemplate = new XTemplate($viewFile);

                // CHECK PERMISSION
                // check add button
                if (Utility::checkPermission('add', $groupFunctions, ITEM_CATEGORY_MANAGEMENT)) {
                    $xtemplate->parse('main.add_button');
                }
                // check delete button
                if (Utility::checkPermission('delete', $groupFunctions, ITEM_CATEGORY_MANAGEMENT)) {
                    $xtemplate->parse('main.delete_button');
                }
                // check enable button
                if (Utility::checkPermission('enable', $groupFunctions, ITEM_CATEGORY_MANAGEMENT)) {
                    $xtemplate->parse('main.enable_button');
                }
                // check disable button
                if (Utility::checkPermission('disable', $groupFunctions, ITEM_CATEGORY_MANAGEMENT)) {
                    $xtemplate->parse('main.disable_button');
                }

                $categoryID = 0;
                if (isset($_POST['slCategoryID'])) {
                    $categoryID = $_POST['slCategoryID'];
                } else if (isset($_GET['categoryID'])) {
                    $categoryID = $_GET['categoryID'];
                }


                $indexCheckBox = 1;


                $rurrentPage = 1;
                if (isset($_POST["page"])) {
                    $rurrentPage = $_POST["page"];
                }

                $index = 1;

                $categories = $this->getCategoryObjectListByComponentID(0);


                $pager = PagerBackEnd::getPagerData(count($categories), $rowToView, $rurrentPage);

                if ($categories != null) {
                    $indexCheckBox = 1;
                    for ($i = 0; $i < count($categories); $i++) {

                        if ($index > $pager->offset && $index <= $pager->limit) {

                            $xtemplate->assign('INDEX', $index);
                            $xtemplate->assign('INDEX_CHECKBOX', $indexCheckBox);
                            $xtemplate->assign('CATEGORY_ID', $categories[$i]->getID());
                            $xtemplate->assign('CATEGORY_TITLE', $categories[$i]->getTitle());
                            $xtemplate->assign('CATEGORY_ORDER', $categories[$i]->getOrder());
                            $xtemplate->assign('CREATED_USER', $categories[$i]->getCreateUser()->getFullname());
                            $xtemplate->assign('MODIFIED_USER', $categories[$i]->getModifiedUser()->getFullname());
                            $xtemplate->assign('CREATED_DATE', $categories[$i]->getCreatedDate());
                            $xtemplate->assign('MODIFIED_DATE', $categories[$i]->getModifiedDate());

                            // check update permission                            
                            if (Utility::checkPermission('update', $groupFunctions, ITEM_CATEGORY_MANAGEMENT)) {
                                $xtemplate->parse('main.category_list.update_button');
                            } else {
                                $xtemplate->parse('main.category_list.update_button_disable');
                            }

                            if ($categories[$i]->getState() == 1) {
                                $xtemplate->assign('STATUS_ACTION', 'unpublish');
                                $xtemplate->assign('STATUS_IMAGE', 'publish_g.png');
                            } else {
                                $xtemplate->assign('STATUS_ACTION', 'publish');
                                $xtemplate->assign('STATUS_IMAGE', 'publish_r.png');
                            }

                            if ($index == 1) {
                                $xtemplate->parse('main.category_list.down_arrow');
                            } else if ($index == count($categories)) {
                                $xtemplate->parse('main.category_list.up_arrow');
                            } else {
                                $xtemplate->parse('main.category_list.up_down_arrow');
                            }

                            $xtemplate->parse('main.category_list');

                            $indexCheckBox++;
                        }
                        $index++;
                    }



                    $xtemplate->assign('LIMIT_LIST', Utility::getLimitList($rowToView));


                    $xtemplate->assign('ROW_TO_VIEW', $rowToView);

                    $xtemplate->assign('CURRENT_PAGE', $rurrentPage);


                    $xtemplate->assign('AMOUNT_OF_PAGE', $pager->numPages);


                    $xtemplate->assign('PAGING_HTML', $pager->paging);
                }
                $xtemplate->parse('main');
                $xtemplate->out('main');
            }
            // add task
            else if ($task == 'add') {
                if (Utility::checkPermission('add', $groupFunctions, ITEM_CATEGORY_MANAGEMENT)) {
                    $xtemplate = new XTemplate($dir . DS . 'views' . DS . 'category' . DS . 'category_add.html');

                    $this->printCategoryList($xtemplate);

                    $xtemplate->assign('TODAY', date('d/m/Y'));
                    $xtemplate->parse('main');
                    $xtemplate->out('main');
                } else {
                    echo ERROR_PERMISSION;
                }
            }
            // eidt task
            else if ($task == 'edit') {
                if (Utility::checkPermission('update', $groupFunctions, ITEM_CATEGORY_MANAGEMENT)) {
                    $categoryID = '';
                    if (isset($_GET['categoryID'])) {
                        $categoryID = $_GET['categoryID'];
                    }

                    $category = $this->getCategoryByID($categoryID);

                    if ($category != null) {
                        $xtemplate = new XTemplate($dir . DS . 'views' . DS . 'category' . DS . 'category_edit.html');

                        $this->printCategoryList($xtemplate, $category->getParent());

                        $xtemplate->assign('CATEGORY_MODIFIED_DATE', $category->getModifiedDate());

                        $xtemplate->assign('CATEGORY_TITLE', $category->getTitle());


                        $xtemplate->assign('CATEGORY_ALIAS', $category->getAlias());

                        $xtemplate->assign('CATEGORY_DESCRIPTION', $category->getDescription());

                        $xtemplate->assign('CATEGORY_ID', $category->getID());

                        if ($category->getState() == 1) {
                            $xtemplate->parse('main.state_true');
                        } else {
                            $xtemplate->parse('main.state_false');
                        }
                        $xtemplate->parse('main');
                        $xtemplate->out('main');
                    } else {
                        Utility::redirect('.?com=com_content&view=category&task=view');
                    }
                } else {
                    echo ERROR_PERMISSION;
                }
            }
        } else {
            Utility::redirect('.');
        }
    }

    // get item list be long to a category id
    private function getItemListByCategoryID($categoryID) {
        try {

            $db = new Database();
            $item = new Items();

            if ($categoryID == 0) {
                return $item->getList($db);
            } else {
                $item->setCategoryID($categoryID);
                return $item->getListByCategoryID($db);
            }
        } catch (PDOException $exc) {
            echo "getItemList error: " . $exc->getMessage();
        }
    }

    // tải danh sách chủ đề (category) theo mã thành phần (component)
    // thành phần này là thành phần bài viết có mã là 2
    private function getCategoryObjectListByComponentID($parentID = 0, $space = '&nbsp;&nbsp;', $rows = null) {
        try {
            if (!$rows) {
                $rows = array();
            }

            $db = new Database();
            $category = new Categories();
            $category->setComponentID(1); // mã thành phần sản phẩm
            $category->setParent($parentID);
            $result = $category->getListByParentIDAndComponentID($db);
            $db->submitChanges();

            if ($result != null) {
                for ($i = 0; $i < count($result); $i++) {
                    $result[$i]->setTitle($space . $result[$i]->getTitle());
                    $rows[] = $result[$i];

                    $rows = $this->getCategoryObjectListByComponentID($result[$i]->getID(), $space . '_|__&nbsp;', $rows);
                }
            }
            return $rows;
        } catch (PDOException $exc) {
            echo "getCategoryListByComponentID error: " . $exc->getMessage();
        }
    }

    // show category list
    private function printCategoryList($xtemplate, $parentID = null) {

        $categories = $this->getCategoryObjectListByComponentID(0);


        foreach ($categories as $category) {
            $xtemplate->assign('CATEGORY_ID', $category->getID());
            $xtemplate->assign('CATEGORY_TITLE', $category->getTitle());



            if ($parentID != null) {
                if ($parentID == $category->getID()) {
                    $xtemplate->assign('SELECTED_CATEGORY', 'selected');
                } else {
                    $xtemplate->assign('SELECTED_CATEGORY', '');
                }
            } else {
                if (isset($_POST['slCategoryID'])) {

                    if ($_POST['slCategoryID'] == $category->getID()) {
                        $xtemplate->assign('SELECTED_CATEGORY', 'selected');
                    } else {
                        $xtemplate->assign('SELECTED_CATEGORY', '');
                    }
                } else if (isset($_GET['categoryID'])) {

                    if ($_GET['categoryID'] == $category->getID()) {
                        $xtemplate->assign('SELECTED_CATEGORY', 'selected');
                    } else {
                        $xtemplate->assign('SELECTED_CATEGORY', '');
                    }
                } else {
                    $xtemplate->assign('SELECTED_CATEGORY', '');
                }
            }
            $xtemplate->parse('main.category_list');
        }
    }

    // print property list
    private function printPropertyList($xtemplate) {
        $db = new Database();
        try {
            $property = new Properties();
            $rows = $property->getList($db);
            $db->submitChanges();
            if (count($rows) > 0) {
                foreach ($rows as $row) {
                    $xtemplate->assign('PROPERTY_ID', $row->getID());
                    $xtemplate->assign('PROPERTY_NAME', $row->getName());
                    $xtemplate->parse('main.property_list');
                }
            }
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
        }
    }

    /**
     * insert item and properties of item into dataabase
     * @param type $code
     * @param type $name
     * @param type $price
     * @param type $categoryID
     * @param type $image: image
     * @param type $alias: alias
     * @param type $state: state of item (1: hide item, 0; show item)
     * @param type $createdDate: created date
     * @param type $userID: $user ID login
     * @param type $arrayProperty: property list of item
     * @return boolean
     */
    private function addItem($code, $name, $price, $categoryID, $image, $alias, $state, $createdDate, $userID, $description, $detail, $arrayProperty) {
        $db = new Database();
        try {
            $item = new Items();
            $item->setCode($code);
            $item->setName($name);
            $item->setCategoryID($categoryID);
            $item->setImage($image);
            $item->setPrice($price);
            $item->setAlias($alias);
            $item->setState($state);
            $item->setCreatedDate($createdDate);
            $item->setModifiedDate($createdDate);
            $item->setCreatedUserID($userID);
            $item->setModifiedUserID($userID);
            $item->setDescription($description);
            $item->setDetail($detail);

            $item->setOrder($item->getMaxOrder($db));

            $lastInsertItemID = $item->add($db);

            if (count($arrayProperty) > 0) {
                foreach ($arrayProperty as $property) {
                    $itemProperty = new ItemProperties();
                    $itemProperty->setItemID($lastInsertItemID);
                    $itemProperty->setPropertyID($property[0]);
                    $itemProperty->setValue($property[1]);
                    $itemProperty->add($db);
                }
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            return false;
        }
    }

    /**
     * update an item and properties of item into dataabase
     * @param type $code
     * @param type $name
     * @param type $price
     * @param type $categoryID
     * @param type $image: image
     * @param type $alias: alias
     * @param type $state: state of item (1: hide item, 0; show item)
     * @param type $createdDate: created date
     * @param type $userID: $user ID login
     * @param type $arrayProperty: property list of item
     * @return boolean
     */
    private function updateItem($itemID, $code, $name, $price, $categoryID, $image, $alias, $state, $modifiedDate, $userID, $description, $detail, $arrayProperty) {
        $db = new Database();
        try {

            // update item
            $item = new Items();
            $item->setID($itemID);
            $item->setCode($code);
            $item->setName($name);
            $item->setCategoryID($categoryID);
            $item->setImage($image);
            $item->setPrice($price);
            $item->setAlias($alias);
            $item->setState($state);
            $item->setModifiedDate($modifiedDate);
            $item->setModifiedUserID($userID);
            $item->setDescription($description);
            $item->setDetail($detail);
            $item->update($db);

            // delete properties of the item
            $itemPropertyToDelete = new ItemProperties();
            $itemPropertyToDelete->setItemID($itemID);
            $itemPropertyToDelete->deleteByItemID($db);


            if (count($arrayProperty) > 0) {
                // add each property of item to item_properties
                foreach ($arrayProperty as $property) {
                    $itemProperty = new ItemProperties();
                    $itemProperty->setItemID($itemID);
                    $itemProperty->setPropertyID($property[0]);
                    $itemProperty->setValue($property[1]);
                    $itemProperty->add($db);
                }
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            return false;
        }
    }

    // get detail of an item
    private function getItemByID($itemID) {
        $db = new Database();
        try {
            $item = new Items();
            $item->setID($itemID);
            return $item->getByID($db);
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            return null;
        }
    }

    // get property list of an item
    private function getItemPropertiesByItemID($itemID) {
        $db = new Database();
        try {
            $itemProperty = new ItemProperties();
            $itemProperty->setItemID($itemID);
            return $itemProperty->getItemPropertiesByItemID($db);
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            return null;
        }
    }

    // hàm cập nhật highlight bài viết
    private function deleteItem($values) {
        $db = new Database();
        try {
            for ($i = 0; $i < count($values); $i++) {
                $item = new Items();
                $item->setID($values[$i]);
                $item->delete($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    // hàm cập nhật trạng thái bài viết
    private function updateItemState($values, $status) {

        try {
            $db = new Database();
            for ($i = 0; $i < count($values); $i++) {
                $item = new Items();
                $item->setID($values[$i]);
                if ($status == true) {
                    $item->setState(1);
                } else {
                    $item->setState(0);
                }
                $item->updateState($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            exit();
        }
    }

    // update category state
    private function updateCategoryState($values, $status) {

        try {
            $db = new Database();
            for ($i = 0; $i < count($values); $i++) {
                $category = new Categories();
                $category->setID($values[$i]);
                if ($status == true) {
                    $category->setState(1);
                } else {
                    $category->setState(0);
                }
                $category->updateState($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            exit();
        }
    }

    // order item
    private function orderItem($itemID, $action) {
        $db = new Database();
        try {
            $item = new Items();
            $item->setID($itemID);
            if ($action == 'up') {
                $item->orderUp($db);
            } else {
                $item->orderDown($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    // hàm tải chi tiết 1 category
    private function getCategoryByID($categoryID) {
        try {
            $db = new Database();
            $category = new Categories();
            $category->setID($categoryID);
            $category = $category->getByID($db);
            $db->submitChanges();
            return $category;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            exit();
        }
    }

    // delete a category
    private function deleteCategory($values) {
        try {
            $db = new Database();
            for ($i = 0; $i < count($values); $i++) {
                $category = new Categories();
                $category->setID($values[$i]);
                $category->delete($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            exit();
        }
    }

    // order category
    private function orderCategory($categoryID, $action) {
        $db = new Database();
        try {

            $category = new Categories();
            $category->setID($categoryID);
            $categoryLevel = $category->getByID($db);
            $category->setComponentID(1); // item category
            $category->setLevel($categoryLevel->getLevel());

            if ($action == 'up') {
                $category->orderUp($db);
            } else {
                $category->orderDown($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    // hàm thêm 1 bài viết
    private function addCategory($parent, $title, $alias, $createdDate, $description, $createdUserID, $status) {
        $db = new Database();
        try {

            $category = new Categories();

            // id cha
            $category->setParent($parent);

            // tieu de
            $category->setTitle($title);
            // alias
            $category->setAlias($alias);

            // ngay tao
            $category->setCreatedDate($createdDate);
            // ngay cap nhat
            $category->setModifiedDate($createdDate);

            // nguoi tao
            $category->setCreatedUserID($createdUserID);
            // nguoi cap nhat
            $category->setModifiedUserID($createdUserID);

            // mo ta
            $category->setDescription($description);
            // trang thai
            $category->setState($status);


            // cap bac
            $category->setLevel($category->getNextLevelByParentID($db));

            // ma thanh phan
            $category->setComponentID(1); // thành phần là nhóm tin
            //
            // thu tu
            $category->setOrder($category->getMaxOrder($db));

            // them category
            $result = $category->add($db);

            $db->submitChanges();
            if ($result > 0) {
                return OK;
            } else {
                
            }
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    // hàm cập nhật 1 bài viết
    private function updateCategory($parent, $title, $alias, $createdDate, $description, $createdUserID, $status, $ID) {
        $db = new Database();
        try {

            $category = new Categories();

            // id cha
            $category->setID($ID);

            // id cha
            $category->setParent($parent);

            // tieu de
            $category->setTitle($title);

            // alias
            $category->setAlias($alias);

            // ngay cap nhat
            $category->setModifiedDate($createdDate);

            // nguoi cap nhat
            $category->setModifiedUserID($createdUserID);

            // mo ta
            $category->setDescription($description);

            // trang thai
            $category->setState($status);


            // cap bac
            $category->setLevel($category->getNextLevelByParentID($db));


            // update category
            $category->update($db);

            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

}

?>
